package linker.window;

import java.awt.*;

import java.awt.event.*;
import java.util.Properties;
import javax.swing.*;

import linker.account.ManageAccount;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jiafeng.linker@gmail.com
 * 
 */

public class LoginWindow extends JFrame implements ItemListener, ActionListener {

	private static final long serialVersionUID = 1L;

	private JButton loginButton;

	private JButton advencedButton;

	private JPasswordField passwordField;

	private JComboBox box;

	private JCheckBox savePassword = new JCheckBox("Save password?");

	private Properties accounts = new Properties();

	private ManageAccount manageAccount = ManageAccount.getManageAccount();

	private JProgressBar bar;

	private String host = null;

	private String port = null;

	private String domain = null;

	public LoginWindow() {
		super("Linker login");
		setName("LoginWindow");

		Toolkit.getDefaultToolkit().addAWTEventListener(
				WindowSaver.getWindowSaver(), AWTEvent.WINDOW_EVENT_MASK);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setIconImage(Toolkit.getDefaultToolkit().createImage(
				ManageAccount.getImagePath() + "logo.png"));

		Container container = getContentPane();
		JPanel p = new JPanel();
		GroupLayout layout = new GroupLayout(p);
		p.setLayout(layout);
		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);

		JLabel nameLabel = new JLabel("Username:");
		accounts = manageAccount.getAccounts();
		box = new JComboBox();
		Object[] names = accounts.keySet().toArray();
		for (int i = 0; i < names.length; i++) {
			String name = (String) names[i];
			if (name.endsWith("host") || name.endsWith("port")
					|| name.endsWith("domain"))
				continue;

			box.addItem(names[i]);
		}
		box.addItemListener(this);
		box.setEditable(true);

		JLabel passwordLabel = new JLabel("Password:");
		passwordField = new JPasswordField(15);

		if (accounts.getProperty((String) names[0]).length() == 0)
			savePassword.setSelected(false);
		else
			savePassword.setSelected(true);

		passwordField.addActionListener(this);
		loginButton = new JButton("Login");
		loginButton.addActionListener(this);
		advencedButton = new JButton("Advenced");
		advencedButton.addActionListener(this);
		savePassword.addItemListener(this);

		layout.setHorizontalGroup(layout.createSequentialGroup().addGroup(
				layout.createParallelGroup(GroupLayout.Alignment.LEADING)
						.addComponent(nameLabel).addComponent(passwordLabel))
				.addGroup(
						layout.createParallelGroup(
								GroupLayout.Alignment.LEADING)
								.addComponent(box).addComponent(passwordField)
								.addGroup(
										layout.createSequentialGroup()
												.addComponent(loginButton)
												.addComponent(advencedButton))
								.addComponent(savePassword)));
		layout.setVerticalGroup(layout.createSequentialGroup().addGroup(
				layout.createParallelGroup(GroupLayout.Alignment.LEADING)
						.addComponent(nameLabel).addComponent(box)).addGroup(
				layout.createParallelGroup(GroupLayout.Alignment.LEADING)
						.addComponent(passwordLabel)
						.addComponent(passwordField))
				.addGroup(
						layout.createParallelGroup(
								GroupLayout.Alignment.BASELINE).addComponent(
								loginButton).addComponent(advencedButton))
				.addGroup(
						layout.createParallelGroup(
								GroupLayout.Alignment.BASELINE).addComponent(
								savePassword)));

		container.add(p, BorderLayout.NORTH);

		container.add(new JSeparator(), BorderLayout.CENTER);

		bar = new JProgressBar();
		bar.setIndeterminate(true);
		bar.setVisible(false);
		container.add(bar, BorderLayout.SOUTH);

		setSize(320, 130);
		setLocationRelativeTo(null);
		try {
			WindowSaver.getWindowSaver().loadSettings(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setVisible(true);
	}

	public void itemStateChanged(ItemEvent e) {
		if (e.getSource() == box) {
			if (box.getSelectedIndex() != -1) {
				String password = accounts.getProperty((String) box
						.getSelectedItem());
				passwordField.setText(password);

				if (password == null || password.length() == 0)
					savePassword.setSelected(false);
				else
					savePassword.setSelected(true);

			} else {
				passwordField.setText("");
				savePassword.setSelected(false);
			}
		}
	}

	public void login() {
		final String username, password;

		if ((box.getSelectedIndex() == -1 && ((JTextField) box.getEditor()
				.getEditorComponent()).getText() == "")
				|| passwordField.getPassword().toString().trim().equals("")) {
			JOptionPane.showMessageDialog(null,
					"You shoud input username and password");
			return;
		}

		if (box.getSelectedIndex() == -1)
			username = ((JTextField) box.getEditor().getEditorComponent())
					.getText();
		else
			username = box.getSelectedItem().toString();
		password = new String(passwordField.getPassword());

		loginButton.setText("Login...");
		loginButton.setEnabled(false);
		bar.setVisible(true);

		Thread t = new Thread(new LoginProgress(this, username, password, null,
				null, null));
		t.start();

		manageAccount.setAccount(username, password, host, port, domain,
				savePassword.isSelected());
	}

	public void changeWindowForLoginFailed() {
		loginButton.setText("Failed");
		loginButton.setEnabled(true);
		bar.setVisible(false);
	}

	public void changeWindowForLogin() {
		new MainWindow();

		this.dispose();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == loginButton || e.getSource() == passwordField) {
			login();
		} else if (e.getSource() == advencedButton) {
			AdvencedAccountSetting.setLoginWindow(this);
		}
	}

	public void setSetting(String host, String port, String domain) {
		this.host = host;
		this.port = port;
		this.domain = domain;
	}
}
